package com.lmh.gpt.demo.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lmh.gpt.demo.model.ChatGptRequest;
import com.lmh.gpt.demo.model.ChatGptResponse;
import com.lmh.gpt.demo.model.Message;
import com.lmh.gpt.demo.service.ChatGptService;
import com.lmh.gpt.demo.util.Contant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;

import java.net.Proxy;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class ChatGptServiceImpl implements ChatGptService {
    @Autowired
    private Environment environment;

    public String sendRequestWithProxy(String question, List<String> context) {
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        // 设置代理主机和端口
        String proxyHost = environment.getProperty("http.proxy.host");
        int proxyPort = environment.getProperty("http.proxy.port", Integer.class);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        requestFactory.setProxy(proxy);

        restTemplate.setRequestFactory(requestFactory);


// 设置请求头
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + Contant.TOKEN);

        // 构建请求体对象
        ChatGptRequest requestBody = new ChatGptRequest();
        // 构建上下文消息
        List<Message> messages = new ArrayList<>();
        // 添加上下文消息
        if (context != null && !context.isEmpty()) {
            // 设置上下文
            for (String ctx : context) {
                Message message = new Message();
                message.setRole("system");
                message.setContent(ctx);
                messages.add(message);
            }
        }

        // 添加用户问题消息
        Message userMessage = new Message();
        userMessage.setRole("user");
        userMessage.setContent(question);
        messages.add(userMessage);



            requestBody.setMessages(messages);
            requestBody.setModel("gpt-3.5-turbo");

            // 创建 ObjectMapper 对象
            requestBody.setMessages(messages);
            requestBody.setModel("gpt-3.5-turbo");

            // 创建 ObjectMapper 对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 将请求体对象序列化为 JSON 字符串
            try {
                String requestBodyString = objectMapper.writeValueAsString(requestBody);
                HttpEntity<String> entity = new HttpEntity<>(requestBodyString, headers);

                ResponseEntity<String> response = restTemplate.exchange(Contant.GPTENDPOINT, HttpMethod.POST, entity, String.class);
                String body = response.getBody();
                System.out.println(body);

                // 创建ObjectMapper对象
                ObjectMapper objectMapper1 = new ObjectMapper();

                // 将JSON字符串转换为Java对象
                ChatGptResponse responseGPT = objectMapper1.readValue(body, ChatGptResponse.class);

                // 从Java对象中获取content值
                String content = responseGPT.getChoices().get(0).getMessage().getContent();
                // 在控制台输出content值
                System.out.println("Content: " + content);
                return content;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

    public String sendRequestWithProxy(String question) {
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        // 设置代理主机和端口
        String proxyHost = environment.getProperty("http.proxy.host");
        int proxyPort = environment.getProperty("http.proxy.port", Integer.class);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        requestFactory.setProxy(proxy);

        restTemplate.setRequestFactory(requestFactory);


// 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + Contant.TOKEN);


        // 构建请求体对象
        ChatGptRequest requestBody = new ChatGptRequest();
        Message message1 = new Message();
        message1.setRole("user");
        message1.setContent(question);

        List<Message> messages = Collections.singletonList(message1);
        requestBody.setMessages(messages);
        requestBody.setModel("gpt-3.5-turbo");

        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 将请求体对象序列化为 JSON 字符串
        try {
            String requestBodyString = objectMapper.writeValueAsString(requestBody);
            HttpEntity<String> entity = new HttpEntity<>(requestBodyString, headers);

            ResponseEntity<String> response = restTemplate.exchange(Contant.GPTENDPOINT, HttpMethod.POST, entity, String.class);
            String body = response.getBody();
            System.out.println(body);

            // 创建ObjectMapper对象
            ObjectMapper objectMapper1 = new ObjectMapper();

            // 将JSON字符串转换为Java对象
            ChatGptResponse responseGPT = objectMapper1.readValue(body, ChatGptResponse.class);

            // 从Java对象中获取content值
            String content = responseGPT.getChoices().get(0).getMessage().getContent();

            // 在控制台输出content值
            System.out.println("Content: " + content);
            return content;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
